
/**
 * Gallery
 * @param {Array} list data
 * @param {number} width waper width
 * @param {number} h
 * @param {number} gap padding
 */
function Gallery(list, waperWidth, h, gap) {
  var L = JSON.parse(JSON.stringify(list)),
    cacheRow = [],
    cacheRowWidth = 0,
    cacheNextWidth = 0,

    thresholdHeight = 5,
    newList = [];

  // 统一图片高度
  L = L.map(function (v) {
    var ratio = v.width / v.height || 1;

    ratio > 3 && ( ratio = 3 );
    ratio < .34 && ( ratio = .34 );

    v._height = h;
    v._width = h * ratio;
    return v;
  });

  // core
  L.forEach(function (v, i, arr) {
    cacheRow.push(v);

    cacheRowWidth += v._width;
    cacheNextWidth = cacheRowWidth + (arr[i+1] ? arr[i+1]._width: 0);

    if (judgment()) {
      var r = cacheRowWidth / waperWidth;

      if (gap) {
        r = cacheRowWidth/(waperWidth - gap*cacheRow.length);
      }

      newList = newList.concat(cacheRow.map(function (item) {
        item._width = item._width / r;
        item._height = item._height / r;

        if (gap) {
          item._width = floor(item._width + gap);
          item._height = floor(item._height + gap);
          item._padding = gap;
        }

        return item;
      }));

      cacheRow = [];
      cacheRowWidth = 0;
    }

    if (i === (L.length - 1)) {
      newList = newList.concat(cacheRow.map(function (item) {
        if (gap) {
          item._width = floor(item._width + gap);
          item._height = floor(item._height + gap);
          item._padding = gap;
        }

        return item;
      }));
    }
  });

  // 换行规则
  function judgment() {

    // 当前实际高度
    var currentH = waperWidth / cacheRowWidth * h;
    if ( currentH < h + thresholdHeight ) {
      return true;
    }

    // 下一个实际高度
    var nextH = waperWidth / cacheNextWidth * h;
    if ( nextH < h - thresholdHeight 
      && currentH < h + thresholdHeight*2
      ) {
      return true;
    }

    return false;
  }

  function floor (num) {
    return Math.floor(num * 100) / 100;
  }

  return newList;
}
